package com.zzyl.serve.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zzyl.serve.domain.*;
import com.zzyl.serve.dto.CheckInApplyDto;
import com.zzyl.serve.dto.CheckInConfigDto;
import com.zzyl.serve.dto.ElderFamilyDto;
import com.zzyl.serve.mapper.CheckInConfigMapper;
import com.zzyl.serve.mapper.ContractMapper;
import com.zzyl.serve.mapper.ElderMapper;
import com.zzyl.serve.service.*;
import com.zzyl.serve.util.CodeGenerator;
import com.zzyl.serve.vo.CheckInConfigVo;
import com.zzyl.serve.vo.CheckInDetailVo;
import com.zzyl.serve.vo.CheckInElderVo;
import com.zzyl.serve.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.serve.mapper.CheckInMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 * 
 * @author king
 * @date 2025-04-29
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Autowired
    private IElderService elderService;

    @Autowired
    private IBedService bedService;

    @Autowired
    private IContractService contractService;

    @Autowired
    private ICheckInConfigService checkInConfigService;


    /**
     * 入住申请
     *
     * @param dto
     */
    @Override
    @Transactional
    public void apply(CheckInApplyDto dto) {
        // 1.判断老人是否已经入住
        // 1.1 通过身份证号、状态，查询老人
        Elder elder = elderService.getOne(
                new LambdaQueryWrapper<Elder>()
                        .eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo())
                        .eq(Elder::getStatus, 1)
        );
        // 1.2 判断老人是否入住: 如果查询不为空，这抛出异常，终止运行；  如果没有查询到，才能开始后续的入住流程
        if(elder != null){
            throw new RuntimeException("该老人已经入住，请勿重复入住");
        }
        // 2.更新床位的状态  已入住
        // 2.1 通过床位id，查询床位
        Bed bed = bedService.getById(
                dto.getCheckInConfigDto().getBedId()
        );
        if(bed.getBedStatus() == 1){
            throw new RuntimeException("该床位已经入住，请勿重复入住");
        }
        // 2.2 更新床位状态
        bed.setBedStatus(1);
        bedService.updateById(bed);
        // 3. 保存或更新老人数据
        // 3.1 准备老人数据： 属性拷贝， 设置床位号、 设置床位id、 设置老人状态
        elder = new Elder();
        BeanUtils.copyProperties(dto.getCheckInElderDto(), elder);
        elder.setBedNumber(bed.getBedNumber());
        elder.setBedId(bed.getId());
        elder.setStatus(1);
        // 3.2 查询老人信息：（身份证号、状态不为1）
        Elder elder1 = elderService.getOne(
                new LambdaQueryWrapper<Elder>()
                        .eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo())
                        .ne(Elder::getStatus, 1)
        );
        // 3.3 如果查到，修改； 如果没有查到，新增
        if(elder1 != null){
            elder.setId(elder1.getId());
            elderService.updateById(elder);
        }else {
            elderService.save(elder);
        }
        // 4. 新增签约办理（保存合同信息）
        // 4.1. 生成合同编号: (使用工具类生成一个16位的合同编号)
        String contractNumber = "HT" + CodeGenerator.generateContractNumber();
        // 4.2 保存合同信息（设置属性，合同号、老人id、老人名字、计算时间设置状态，合同开始结束时间，插入保存）
        Contract contract = new Contract();
        BeanUtils.copyProperties(dto.getCheckInContractDto(), contract);
        contract.setContractNumber(contractNumber);
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        contract.setStartDate(dto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(dto.getCheckInConfigDto().getEndDate());
        if(contract.getStartDate().isBefore(LocalDateTime.now())){
            contract.setStatus(1);
        }else {
            contract.setStatus(0);
        }
        contractService.save(contract);

        // 5. 新增入住信息 （设置属性，插入保存）
        CheckIn checkIn = new CheckIn();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkIn);
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setStatus(0);
        checkIn.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));
        this.save(checkIn);

        // 6. 新增入住配置信息：（属性拷贝，设置关联id，插入保存）
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigService.save(checkInConfig);
        // 7. 事务控制
    }
    @Autowired
    private ContractMapper contractMapper;
    /**
     * 入住详情
     *
     * @param id
     * @return
     */
    @Override
    @Transactional
    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        //查入住信息
        CheckIn checkIn = checkInMapper.selectCheckInById(id);
        //查询老人信息
        Elder elder = elderService.getById(checkIn.getElderId());
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder, checkInElderVo);
        //通过老人身份证号码给checkInElderVo的age属性赋值
        String idCardNo = checkIn.getIdCardNo();
        if (idCardNo == null || idCardNo.length() != 18) {
            throw new IllegalArgumentException("身份证号长度无效");
        }
        String birthDateStr = idCardNo.substring(6, 14);

        // 创建日期解析格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        LocalDate birthDate = LocalDate.parse(birthDateStr, formatter);
        LocalDate currentDate = LocalDate.now();
        if (birthDate.isAfter(currentDate)) {
            throw new IllegalArgumentException("出生日期不合法");
        }
        int age = Period.between(birthDate, currentDate).getYears();
        checkInElderVo.setAge(age);
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        Long elderId = checkIn.getElderId();
        //查询合同信息
        Contract contract = contractMapper.selectOne(new QueryWrapper<Contract>().eq("elder_id", elderId));
        checkInDetailVo.setContract(contract);
        //通过id查询家属信息
        List<ElderFamilyVo> elderFamilyVoList = new ArrayList<>();
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);
        String remark = checkInMapper.selectCheckInById(id).getRemark();
        if (remark != null) {
            List<ElderFamilyDto> elderFamilyDtoList = JSON.parseArray(remark, ElderFamilyDto.class);
            for (ElderFamilyDto elderFamilyDto : elderFamilyDtoList) {
                ElderFamilyVo elderFamilyVo = new ElderFamilyVo();
                BeanUtils.copyProperties(elderFamilyDto, elderFamilyVo);
                elderFamilyVoList.add(elderFamilyVo);
            }
            checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);
        }
        //查询入住配置信息
        CheckInConfig checkInConfig = checkInConfigService
                .getOne(new LambdaQueryWrapper<CheckInConfig>().eq(CheckInConfig::getCheckInId, id));
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        //整合数据返回
        return checkInDetailVo;
    }
}















